<?php
/**
 * Created by PhpStorm.
 * User: function
 * Date: 2018-04-12
 * Time: 20:47
 */

namespace app\common\logic;
use app\common\logic\Logic;
use Auth\OAuthLoginClass;
use app\common\model\Member;
use app\common\model\Address;
use think\Cache;
use app\common\model\Points;
use app\common\model\Amount;
use app\common\model\Card;

use app\common\model\Comment;
use app\common\model\Favorite;
use app\common\model\Info;
class MemberLogic extends Logic
{
    protected $modelClass = 'app\common\model\Member';
    protected $logic;
    
    protected $register = [
        'name'  =>  'require|max:25',
        'email' =>  'email',
    ];

    protected $snslogin_wap_rule = [
        'channel|渠道类型' => 'require',
        'code' => 'require',
        'state' => 'require',
    ];
    
    protected $snslogin_app_rule = [
        'openid' => 'require',
        'accessToken' => 'require'
    ];
    
    
    public function getExtInfo($userId){
        $user = Member::get($userId);
    
        $user['commentCount'] = Comment::where('user_id',$userId)->count();
        $user['infoCount'] = Info::where('user_id',$userId)->count();
        $user['favoriteMallCount'] = Favorite::where('user_id',$userId)->where('type',1)->count();
        $user['favoriteCompanyCount'] = Favorite::where('user_id',$userId)->where('type',2)->count();
        
        return $user;
    }
    


    
    
    /**
     * @param $itemid
     * @param null $field
     * @param $mall 是否需要返回推荐的商品，如果该值为真，则返回店里十个按排名的商品
     * @return mixed
     */
    public function getOne($itemid,$field=null,$mallSize=false){
    
    }
    
    protected function getAccessToken($id){
        $rt = [
            'access_token'=>null,
            'token_expire'=>null,
        ];
        
        $member = Member::get($id);
        if(!$member)return $rt;
        $rt['access_token'] = $member['token'];
        $rt['token_expire'] = $member['token_expire'];
        $rt['wx_pub_openid'] = $member['wx_pub_openid'];
        $rt ['is_bind_phone'] = isset($member['phone'])&&$member['phone']!=''?1:0;
        return $rt;
    }
    
    protected function doLogin($id){
        
        $member = Member::get($id);
        if(!$member){
            return callerror('登陆失败');
        }
        if(!isset($member->token)||$member->token_expire<time()){
            $member->token = md5(time().uuid().randString(32));//利用随机数和open_id生成access-token
            $member->token_expire = time()+7*3600*24;//保存一周
        }
        Cache::set($member->token,$member->id);//全局有个user_id就好了
        $member->save();
    }
    
    /**
     * @param $params
     * @return array
     * @throws \think\exception\DbException
     * @desc 能到这里的一定是手机号和密码都校验过了的，可以直接用...
     */
    public function login($params){
        
        $member = Member::get(['phone'=>$params['phone']]);
        if(!$member){
            return callerror('用户不存在');
        }
        $password = base64_encode(hash('sha256', ($params['password'].$member['passsalt']),true));
        if($password!=$member['password']){
            return callerror('密码错误');
        }
        
        $this->doLogin($member['id']);
        
        $token = $this->getAccessToken($member['id']);
        if($token['access_token']){
            return callsuccess($token);
        }else{
            return callerror('登陆失败');
        }
        
        
    }
    
    /**
     * @desc 注销登录
     */
    public function  logout(){
        Cache::rm($this->accessToken);
    }
    
    
    public function changeInfo($id,$column,$attr){
        
        $member = Member::get($id);
        $member[$column] = $attr;
        $rt = $member->isUpdate()->save();
        return $rt?true:false;
    }
    

    
    public function getOrder(){
    
    }
    
    public function baseInfo(){
    
    }
    
    public function add($params){
        
        $salt = base64_encode(sha1(openssl_random_pseudo_bytes(32), true));
        $params['passsalt'] = $salt;
        $params['password'] =  base64_encode(hash('sha256', ($params['password'] . $salt), true));
        if(isset($params['username'])){
        
        }
        $rt  = parent::add($params);
        return $rt;
    }
    
    
    /**
     * @desc 第三方账号统一登陆接口
     * @param $channel
     * @param $code
     * @param $state
     */
    public function snsLogin($channel,$code,$state){
        
        switch ($channel){
            //到这里终于一样的了
            case 'wechat_pub':
                
                $memberInfo = OAuthLoginClass::authLogin('wechat_pub',$code,$state);
//                if(!isset($memberInfo['unionid'])){
//                    error('获取用户信息失败');
//                }
//                $member = Member::get(['wx_union_id'=>$memberInfo['unionid']]);
                $member = Member::get(['wx_pub_openid'=>$memberInfo['openid']]);
                //新用户注册
                if(!isset($member)){
                    
                    $member = new Member();
                    $member->nickname = $memberInfo['nickname'];
                    $member->province = $memberInfo['province'];
                    $member->city = $memberInfo['city'];
                    $member->headimgurl = $memberInfo['headimgurl'];
                    $member->wx_pub_openid = $memberInfo['openid'];
//                    $member->wx_union_id=$memberInfo['unionid'];
                    $member->nickname = $memberInfo['nickname'];
                    $member->sex = $memberInfo['sex'];
                    $member->login_num=0;
                    $member->save();//保存一下
                    
                    //新用户注册给积分
                    //$member->changePoint(20,7,1,'注册奖励积分');
                    
                    
                }
                break;
            default:
                return callerror('第三方登陆接口channel参数错误');
                break;
        }
        
        $this->doLogin($member->id);

        $memberinfo = Member::get($member->id);
        $result=[
            'access-token'=>$memberinfo->token,
            'token_expire'=>$memberinfo->token_expire,
            'wx_pub_openid' => $memberinfo->wx_pub_openid,
            'is_bind_phone'=>isset($memberinfo->phone)&&$memberinfo->phone!=''?1:0
        ];
        
        return callsuccess($result);
//        return ;
        
    }
    
    
    /**
     * @desc 修改积分
     * @param $action 默认是1，为加积分，设置为-1为减积分
     * @param $number 变动的数量
     * @param $type  积分变动的类别 //获取积分方式，1签到，2购买，3分享，4收藏，5评论，6下载app，7新注册用户，8拉人注册,9推荐商品，他人点击成交后获得积分奖励
     * @param string $content //描述
     * @return bool
     */
    public function changePoint($userId,$number,$type,$action=1,$content='积分变动'){
    
        $user = Member::get($userId);
        
        $points = new Points();
        
        if(!isset($number)||!isset($action)||!isset($type)){
            return false;//参数缺失
        }
        //积分不够就别干了
        if($user->pionts_num +$action*$number<0){
            return false;
        }
        $params =[
            'user_id'=>$this->id,
            'before_points'=>$user->pionts_num,//从用户的额外信息表里面拿现在的积分
            'number'=>$number,
            'after_points'=>$user->pionts_num +$action*$number,//判断是否大于0
            'type'=>$type,
            'action'=>$action,
            'content'=>$content
        ];
        $rt1 = $points->allowField(true)->save($params);
        
        if(!$rt1){
            return false;
        }
    
        $user->pionts_num +=$action*$number;//如果为正就加，如果为负就减
        $rt2 = $user->save();
        
        if(!$rt2){
            return false;
        }
        
        return true;
        
        
    }
    
    
    /**
     * @desc 修改金额
     * @param $action 默认是1，为加积分，设置为-1为减积分
     * @param $number 变动的数量
     * @param $type  金额变动的类别 //金额变动类型，1为提现，2为分销收入,3为充值
     * @param string $content //描述
     * @return bool
     * 提现的订单guid，就是订单id
     */
    public function changeAmount($userId,$number,$type,$action=1,$content='余额变动',$order_id,$widhDraw=null){
        
        $user = Member::get($userId);
        $amount = new Amount();
        
        if(!isset($number)||!isset($action)||!isset($type)){
            return false;//参数缺失
        }
        
        //不够就别干了
        if($user->cashing_money +$action*$number<0){
            return false;
        }
        
        $params =[
            'user_id'=>$this->id,
            'before_total_amount'=>$user->cashing_money,//从用户的额外信息表里面拿现在的积分
            'amount'=>$number,
            'after_total_amount'=>$user->cashing_money +$action*$number,//判断是否大于0
            'type'=>$type,
            'action'=>$action,
            'content'=>$content,
            'order_id'=>$order_id,
            'widthDraw'=>$widhDraw
        ];
        $rt1 = $amount->allowField(true)->save($params);
        
        if(!$rt1){
            return false;
        }
    
        $user->cashing_money +=$action*$number;//如果为正就加，如果为负就减
        $rt2 = $user->save();
        if(!$rt2){
            return false;
        }
        
        return true;
        
        
    }
    
  
    
}